var 
    express = require('express'),
    router = express.Router(),
    uuid = require('uuid'),
    mongos = require('../service/mongodb');



router.post('/score', function(req, res) {
    var _d = req.body;
    var tid = _d.tid;
    var score = parseInt(_d.score);

    mongos.get('topics',{tid:tid})
    .then(function (doc){
        
        doc.ratenum = doc.ratenum + 1;
        doc.rate = (doc.rate + score) / doc.ratenum;
        return mongos.update('topics',{tid:tid},doc);
    })
    .then(function (doc){
        res.send(doc);
    });   
});


router.get('/tag/:tag', function(req, res) {
    var tag = req.params.tag;

    mongos.find('topics',{tags:tag},'startdate:desc')
    .then(function(docs){
        res.send(docs);  
    });   
});


//list
router.get('/topics', function(req, res) {
    var all = req.query.all;

    mongos.find('topics',{status:1},'startdate:desc')
    .then(function(docs){
        var _curr = new Date();
        for(var i=0,l=docs.length;i<l;i++){
            docs[i].valid = (docs[i].startdate > _curr);
        }
        res.send(docs);  
    });   
});

//get
router.get('/topic/:id', function(req, res) {
    var id = req.params.id;
    var topic;
    var query = {};
    if('hot' == id){
        mongos.get('homepageconfig',{})
        .then(function(doc){
            return mongos.get('topics',{'tid':doc.hottopic});
        })
        .then(function(doc){
            doc.valid = (doc.startdate > new Date());
            res.send(doc);             
        });          
    }else{
        mongos.get('topics',{'tid':id})
        .then(function(doc){
            doc.valid = (doc.startdate > new Date());
            res.send(doc);  
        });          
    }   
});

//get
router.post('/enroll', function(req, res) {
    var ed = req.body;
    var enrolldata = ed.enroll;
    enrolldata.tid = ed.topic.tid;
    enrolldata.enrollDate = new Date();

    mongos.insert('enroll',enrolldata)
    .then(function(doc){
        console.log(doc);
        res.send({code:200});
    });     
});

module.exports = router;